package org.liang.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.liang.constants.UserConstants;
import org.liang.domain.User;
import org.liang.exception.BusinessException;
import org.liang.exception.ResponseCode;
import org.liang.exception.RonghuaAssert;
import org.liang.service.IUserService;
import org.liang.service.IVerifyCodeService;
import org.liang.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public void userRegisterSendSms(String phone) {
        //校验手机是否被注册
        User user = userService.selectOne(new EntityWrapper<User>().eq("phone", phone));
        RonghuaAssert.isNull(user, ResponseCode.RESPONSE_CODE_400005);

        //发送短信验证码
        String code = VerifyCodeUtils.generateVerifyCode(6, "0123456789");
        //一个手机只能发送一次请求
        //先获取phone看是否发送
        String key = UserConstants.USER_REGISTER_SEND_SMS_KEY + ":" + phone;
        Object codeInRedis = redisTemplate.opsForValue().get(key);
        if(codeInRedis!=null){ //不为空说明发送给也没过期
            //让当前时间-上一次时间<60s  就表示这60s内都算不合法请求
            String codeInRedisStr = codeInRedis.toString();
            code = codeInRedisStr.split(":")[0];
            Long preTime = Long.valueOf(codeInRedisStr.split(":")[1]);
            if(System.currentTimeMillis()-preTime<60*1000){
                throw new BusinessException(ResponseCode.RESPONSE_CODE_400008);
            }
        }

        //开始给用户发送（此处省略）
        System.out.println(code);

        //存储到redis
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
    }
}
